package com.adopapa.ethexplorer.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.adopapa.ethexplorer.domain.TransactionInfo;
import com.adopapa.ethexplorer.domain.TransactionInfoRepository;
import com.adopapa.ethexplorer.utils.Tools;

@Service
public class TransactionInfoService extends BaseService {

	@Autowired
	private TransactionInfoRepository transactionInfoRepository;

	public TransactionInfo getTransactionInfoById(String id) {
		Optional<TransactionInfo> optional = transactionInfoRepository.findById(id);
		return optional.isPresent() ? optional.get() : null;
	}

	public TransactionInfo getTransactionInfoByHash(String hash) {
		List<TransactionInfo> results = transactionInfoRepository.findByHash(hash);
		return Tools.empty(results) ? null : results.get(0);
	}

	public Page<TransactionInfo> getTransactionInfoPage(int pageNo, int pageSize, TransactionInfo transactionInfo) {
		PageRequest pageRequest = QueryHelper.buildPageRequest(pageNo, pageSize, Order.desc("timestamp"));
		Specification<TransactionInfo> specification = QueryHelper.buildSpecification(transactionInfo);
		Page<TransactionInfo> page = transactionInfoRepository.findAll(specification, pageRequest);
		return page;

	}

	public Long getTransactionNumber() {
		return transactionInfoRepository.count();
	}

	public TransactionInfo saveTransactionInfo(TransactionInfo transactionInfo) {
		return transactionInfoRepository.saveAndFlush(transactionInfo);
	}

	public List<TransactionInfo> saveTransactionInfos(List<TransactionInfo> transactionInfos) {
		return transactionInfoRepository.saveAllAndFlush(transactionInfos);
	}

	public void delete(String id) {
		transactionInfoRepository.deleteById(id);
	}

	public void delete(TransactionInfo transactionInfo) {
		transactionInfoRepository.delete(transactionInfo);
	}

}
